#!/usr/bin/env python

import argparse
import sys
import os
import urllib2
import urllib
import re

parser = argparse.ArgumentParser(description= """
DESCRIPTION
    Download fastq files from Genologics given a RUN ID and SLX ID
    
EXAMPLE
    getFastqFromRunID.py -r 130902_HWI-ST230_0650_C2F15ACXX -s SLX-7486

NOTES:
    Not sure if non-multiplexed files will be in 'demultiplex' dir
   
""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('--runid', '-r',
                   required= True,
                   help='''Run ID to get fastq files from. Get this ID from Gord's run notifier.
Typically this looks like '130902_HWI-ST230_0650_C2F15ACXX'

''')

parser.add_argument('--slxid', '-s',
                   required= True,
                   help='''SLX ID to subset all the fastq files from a run.

''')

parser.add_argument('--http',
                   required= False,
                   default= 'http://genomicsequencing.cruk.cam.ac.uk:8080/glsintapi',
                   help='''HTTP address to get the xlm file from. Defualt:
http://genomicsequencing.cruk.cam.ac.uk:8080/glsintapi
''')

parser.add_argument('--echo', '-e', action= 'store_true', help= '''Do not download the files, only show the addresses''')



args= parser.parse_args()

## Prepare HTTP address
http= args.http.strip().rstrip('/') + '/' + 'fullDetailsOfRun?runId=' + args.runid
print('Querying: %s' %(http))

## Get XML file
try:
    run_xml= urllib2.urlopen(http)
except urllib2.URLError:
    sys.exit('Cannot open http\n%s' %(http))    

xml= run_xml.read()
print(xml)

## Get lines with fastq URL Runs/130902_HWI-ST230_0650_C2F15ACXX/demultiplex/SLX-7486
fastqre= '<url>.*/Runs/' + args.runid + '/fastq/' + args.slxid + '.*\.fq\.gz</url>'
print(fastqre)
fastqLines= re.findall(fastqre, xml, re.IGNORECASE)
nfiles= len(fastqLines)
if nfiles == 0:
    sys.exit('No lines in XML matching pattern')
else:
    print('%s files found' %(nfiles))

# Downlaod
fastqhttp= [x.strip().lstrip('<url>').rstrip('</url>') for x in fastqLines]
for url in fastqhttp:
    print(url)
    file_name = url.split('/')[-1]
    if not args.echo:
        u = urllib.urlretrieve(url, file_name)

sys.exit()

